package com.tomato.tv.activity

import android.media.MediaPlayer
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.SurfaceHolder
import com.tomato.tv.R
import kotlinx.android.synthetic.main.activity_media_player.*
import javax.security.auth.callback.Callback

class MediaPlayerActivity : AppCompatActivity() {

   // private val url = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4"
    //private val url = "https://media.w3.org/2010/05/sintel/trailer.mp4"
    private val url = "rtsp://192.168.4.148:8554/lonbon"

    lateinit var mediaPlayer:MediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_player)

        initPlayer()
    }

    private fun initPlayer() {
        mediaPlayer = MediaPlayer()

        surfaceView.holder.addCallback(object:SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                mediaPlayer.setDataSource(applicationContext, Uri.parse(url))
                mediaPlayer.setSurface(surfaceView.holder.surface)
                mediaPlayer.prepareAsync()
                mediaPlayer.setOnPreparedListener {
                    it.start()
                }
            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
            }
        })
    }

    override fun onDestroy() {
        mediaPlayer.stop()
        mediaPlayer.release()
        surfaceView.holder.surface.release()
        super.onDestroy()
    }
}